﻿using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Yz.Base;
using Yz.Core.Apis;
using Yz.Core.Extensions;

namespace Yz.ApiService.Filters
{
    public class TokenAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var context = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            var nvList = context.Request.Headers;
            var token = nvList.Get("token");
            var clientId = nvList.Get("clientId");
            if (string.IsNullOrEmpty(token)) token = context.Request.Params["token"];
            if (string.IsNullOrEmpty(clientId)) clientId = context.Request.Params["clientId"];
            if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(clientId))
            {
                var dtNow = DateTime.Now;
                var appId = BaseConfig.AppId;
                var appSecret = BaseConfig.AppSecret;
                var clientId1 = (appId + dtNow.ToString("yyyyMMddHH")).ToMd5Hash();
                var clientId2 = (appId + dtNow.AddMinutes(BaseConfig.TokenTime).ToString("yyyyMMddHH")).ToMd5Hash();
                var clientId3 = (appId + dtNow.AddMinutes(-BaseConfig.TokenTime).ToString("yyyyMMddHH")).ToMd5Hash();

                var token1 = (appId + appSecret + dtNow.ToString("yyyyMMddHH")).ToMd5Hash();
                var token2 = (appId + appSecret + dtNow.AddMinutes(BaseConfig.TokenTime).ToString("yyyyMMddHH")).ToMd5Hash();
                var token3 = (appId + appSecret + dtNow.AddMinutes(-BaseConfig.TokenTime).ToString("yyyyMMddHH")).ToMd5Hash();
                if ((clientId1 == clientId || clientId2 == clientId || clientId3 == clientId) &&
                    (token == token1 || token == token2 || token == token3))
                {
                    HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
                    return;
                }
            }
            HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
            actionContext.Response = actionContext.Request.CreateResponse(
                ApiDataFactory.CreateApiData(new ApiModel(), ApiDataCode.tokenFail, ApiDataMsg.tokenFail));
        }

    }
}